<script lang="ts" setup>
import { NDrawer, NDrawerContent, NForm, NFormItem, NTreeSelect, NInput } from "naive-ui";
import type { FormInst, FormRules, TreeSelectOption } from "naive-ui";
import { ref } from "vue";
import { getPermissions } from "@/api/user";
import type { Permission } from "@/typings/permission";

interface Props {
  title?: string;
}
const props = withDefaults(defineProps<Props>(), {
  title: "新建",
});

interface FormModelType {
  parentId: number | null;
  name: string;
  path: string;
  component: string;
}

// 表单数据
const formModel = ref<FormModelType>({
  parentId: null,
  name: "",
  path: "",
  component: "",
});

// 表单校验规则
const formRules: FormRules = {
  name: [{ required: true, message: "请先输入菜单名称", trigger: ["blur"] }],
  path: [{ required: true, message: "请先输入菜单路由地址", trigger: ["blur"] }],
  component: [{ required: true, message: "请先输入菜单路由地址", trigger: ["blur"] }],
};

// 树形控件下拉项
let treeSelectOption: TreeSelectOption[] = [];

// 获取树形控件
const getMenus = async () => {
  try {
    const { success, data } = await getPermissions();
    if (!success) return;
    treeSelectOption = convertTreeSelectOption(data);
  } catch (error) {}
};

// 转换下拉项
const convertTreeSelectOption = (data: Permission[]): TreeSelectOption[] => {
  return data.map((item) => {
    const { name, id, children, ...baseValue } = item;
    const option: TreeSelectOption = {
      label: item.name,
      key: item.id,
      ...baseValue,
    };
    if (item.children) {
      option.children = convertTreeSelectOption(item.children);
    }
    return option;
  });
};

getMenus();

// 更新treeSelect选中
const updateTreeValue = (
  value: string | number | Array<string | number> | null,
  option: TreeSelectOption | null | Array<TreeSelectOption | null>
) => {
  formModel.value.parentId = value as number;
};

const isShow = ref(false);

// 控制展示
const controlVisible = () => {
  isShow.value = !isShow.value;
};

// 表单实例
const formRef = ref<FormInst | null>(null);

defineExpose({ controlVisible });
</script>

<template>
  <div>
    <NDrawer v-model:show="isShow" width="40%">
      <NDrawerContent :title="props.title" closable>
        <NForm ref="formRef" :model="formModel" :rules="formRules" label-placement="left" label-width="auto">
          <NFormItem label="上级菜单">
            <NTreeSelect :options="treeSelectOption" @update:value="updateTreeValue" />
          </NFormItem>
          <NFormItem label="菜单名称" path="name">
            <NInput v-model:value="formModel.name" />
          </NFormItem>
          <NFormItem label="路由地址" path="path">
            <NInput v-model:value="formModel.path" />
          </NFormItem>
        </NForm>
      </NDrawerContent>
    </NDrawer>
  </div>
</template>

<style lang="less" scoped></style>
